package com.xjrh.travel.data.apply.config.job;

import com.alibaba.fastjson.JSONObject;
import com.xjrh.travel.core.utils.DateUtils;
import com.xjrh.travel.data.apply.jna.WaveCheckJna;
import com.xjrh.travel.data.apply.service.StationWaveCheckService;
import com.xjrh.travel.data.apply.service.StationWaveDetectionService;
import com.xjrh.travel.entity.wave.StationWaveCheck;
import com.xjrh.travel.entity.wave.StationWaveDetection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Date;

/**
 * 轨道波磨检测-定时任务
 *  <p>
 *      调用第3版的C++算法
 *  </p>
 *
 * @author snps
 * @create 2025-10-31 8:22
 * @describe
 **/
@Component
@EnableScheduling
@Slf4j
public class WaveCheckJob {

    /** 波磨算法返回结果-正常值 */
    private static final int BOMO_SUCCESS_RESULT = 0;

    /** 轨道波磨算法需要的文件存储路径 */
    @Value("${project.waveFileRootPath}")
    private String waveFileRootPath;


    @Resource
    private StationWaveDetectionService stationWaveDetectionService;

    @Resource
    private StationWaveCheckService stationWaveCheckService;


    /**
     * 每5分钟，执行定时任务-调用波磨算法
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    @Async("asyncTaskScheduler")
    public void doWaveCheck() {
        log.info("执行定时任务-调用波磨算法，时间：{}", DateUtils.getDate2String(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS));

        // 获取一个没有执行算法的波磨检测任务（t_station_wave_detection数据）
        String dataDate = DateUtils.getDate2String();
        StationWaveDetection stationWaveDetection = stationWaveDetectionService.getOneNoCheckData(dataDate);
        if (stationWaveDetection == null) {
            return;
        }
        // 把波磨检查结果设置为99，区别于null和0，代表此数据已进行过波磨算法检查
        stationWaveDetection.setWaveCheckResult(99);
        stationWaveDetectionService.setResult(stationWaveDetection);

        // TODO 1-调用波磨算法
        String dataStartTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, stationWaveDetection.getStartTime());
        String dataEndTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, stationWaveDetection.getEndTime());
        String waveFilePath = waveFileRootPath + stationWaveDetection.getWaveFilePath();
        log.info("waveFilePath: {}", waveFilePath);
        String speedFilePath = waveFileRootPath + stationWaveDetection.getSpeedFilePath();
        log.info("speedFilePath: {}", speedFilePath);
        String paramFilePath = waveFileRootPath + stationWaveDetection.getParamFilePath();
        log.info("paramFilePath: {}", paramFilePath);
        String resultFilePath = waveFileRootPath + stationWaveDetection.getResultFilePath();
        log.info("resultFilePath: {}", resultFilePath);
        // System.out.println("java.library.path: " + System.getProperty("java.library.path"));
        log.info("加载动态链接库");
        System.loadLibrary ("WaveCheck");
        log.info("加载动态链接库...ok");

        long lStartTime = System.currentTimeMillis();
        // 定义波磨算法返回结果值
        int result = -1;
        try {
            log.info("执行调用SO文件的bomo方法...");
            result = WaveCheckJna.INSTANCE.bomo(dataStartTime, dataEndTime, waveFilePath, speedFilePath, paramFilePath, resultFilePath);
            long lEndTime = System.currentTimeMillis();
            stationWaveDetection.setWaveCheckResult(result);
            stationWaveDetection.setWaveCheckSecond((int) (lEndTime - lStartTime) / 1000);
            log.info("调用波磨算法时间：{}", stationWaveDetection.getWaveCheckSecond());
            log.info("调用波磨算法文件，运行结果: {}", stationWaveDetection.getWaveCheckResult());
            log.info("波磨算法执行后的结果文件：{}", resultFilePath);
        } catch (Exception e) {
            log.error("调用波磨算法出现异常!");
            e.printStackTrace();
        }

        // TODO 2-如果调用波磨算法成功，读取结果文件的内容并解析处理
        if (result == BOMO_SUCCESS_RESULT) {
            StationWaveCheck stationWaveCheck = null;
            RandomAccessFile readFile = null;
            long fileSize = 0;

            try {
                readFile = new RandomAccessFile(new File(resultFilePath), "r");
                fileSize = readFile.length();
                byte[] arysByte = new byte[(int) fileSize];
                readFile.read(arysByte);
                String content = new String(arysByte);

                // TODO 读取到的文件内容转换为数据并保存
                stationWaveCheck = JSONObject.parseObject(content, StationWaveCheck.class);
                stationWaveCheck.setDataDate(stationWaveDetection.getDataDate());
                stationWaveCheck.setLineNo(stationWaveDetection.getLineNo());
                stationWaveCheck.setTrainNo(stationWaveDetection.getTrainNo());
                stationWaveCheck.setRunningDirection(stationWaveDetection.getRunningDirection());
                stationWaveCheck.setCurrentStation(stationWaveDetection.getStartStation());
                stationWaveCheck.setNextStation(stationWaveDetection.getEndStation());
                stationWaveCheck.setTrackDirection(stationWaveDetection.getTrackDirection());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    readFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // TODO 2025-10-31  人为修改波磨检测结果为：全部正常，无波磨
            stationWaveCheck.setWaveCount(0);
            stationWaveCheck.setWaveData(null);
            // 保存：波磨检查结果 & 检查结果详细数据
            stationWaveCheckService.save(stationWaveCheck);
        }

        // TODO 3-设置波磨检测任务执行结果
        stationWaveDetectionService.setResult(stationWaveDetection);
    }


}